import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:my_ebook_app/models/book.dart';
import 'package:path/path.dart' as path;
import 'package:http/http.dart' as http;
import 'dart:convert';

import '../models/ReadingParams.dart';
import '../models/catalogue.dart';

class BookshelfPage extends StatefulWidget {
  @override
  _BookshelfPageState createState() => _BookshelfPageState();
}

class _BookshelfPageState extends State<BookshelfPage> with WidgetsBindingObserver{
  int _selectedIndex = 1;
  bool _isFilterActive = false;
  String _defaultBook = '杀死一只知更鸟';
  int _sortState = 0; // 0: 默认, 1: 降序, 2: 升序
  final List<BookShelf> _originalBooks = [];
  List<BookShelf> _displayedBooks = [];
  late ReadingBook readingBook;
  late Catalogue bookCatalogue;
  final Map<String, double> bookCatalogues= {};
  String? _filterText = '';
  bool _isLoading = true;
  String _errorMessage = '';


  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _fetchBookShelf();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _fetchBookShelf();
    }
  }
  Future<void> _fetchBookShelf() async {
    try {
      setState(() {
        _isLoading = true;
        _originalBooks.clear(); // 清除旧数据
      });
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/bookDetail/getBookShelf'));

      if (response.statusCode == 200) {
        final List<dynamic> data = json.decode(response.body);
        for( int i=0 ; i< data.length ; i++) {
          _originalBooks.add(BookShelf(
              title: data[i]['bookName'],
              author: data[i]['author'],
              image: 'lib/common/images/${path.basename(data[i]['bookCover'])}',
              progress: (data[i]['progress'] as num).toDouble(),
            ));
        }
        setState(() {
          _isLoading = false;
          _errorMessage = '';
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
    setState(() {
      _displayedBooks = List.from(_originalBooks);
    });
  }

  Future<void> _fetchReadingBook(String bookName) async {
    try {
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/reading/info?bookName=${bookName}'));

      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
        readingBook = ReadingBook(
          title: data['bookName'],
          totalChar: data['totalChar'],
          epubPath: data['bookAddress'],
          progress: (data['progress'] as num).toDouble(),
          localPath: data['localBookAddress'],
        );

        setState(() {
          _isLoading = false;
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      print('错误: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
  }

  Future<void> _fetchBookCatalogue(String bookName) async {
    try {
      final response = await http.get(Uri.parse('http://10.0.2.2:8080/reading/catalogue?bookName=${bookName}'));

      if (response.statusCode == 200) {
        final dynamic data = json.decode(response.body);
        for( int i=0 ; i< data.length ; i++){
          bookCatalogues[data[i]['chapterName']] = (data[i]['chapterPosition'] as num).toDouble();
        }
        bookCatalogue = Catalogue(
          bookName: bookName,
          bookCatalogues: bookCatalogues,
        );

        setState(() {
          _isLoading = false;
        });
      } else {
        setState(() {
          _isLoading = false;
          _errorMessage = '加载失败: ${response.statusCode}';
        });
      }
    } catch (e) {
      print('错误: $e');
      setState(() {
        _isLoading = false;
        _errorMessage = '错误: $e';
      });
    }
  }

  void _handleReadingBook(String bookName) async {
    await _fetchReadingBook(bookName);
    await _fetchBookCatalogue(bookName);
    final result = await context.push('/reading',
        extra: ReadingParams(readingBook, bookCatalogue));

    if (result == 'progress_updated') {
      print('检测到进度更新，刷新书架数据');
      await _fetchBookShelf();
    } else {
      print('没有检测到进度更新');
    }
  }
  // 筛选逻辑
  // 显示一个对话框，让用户输入筛选条件
  void _applyFilter(String filterType) {
    showDialog(context: context,
      builder: (BuildContext context) {
        TextEditingController controller = TextEditingController();
        return AlertDialog(title: Text("请输入$filterType"),
          content: TextField(controller: controller,
            decoration: InputDecoration(hintText: "输入$filterType"),
          ),
          actions: [
            TextButton(
              onPressed: () {
                setState(() {_isFilterActive = true;
                  _filterText = controller.text;
                  if (_filterText!.isEmpty) {
                    _displayedBooks = List.from(_originalBooks);
                    _isFilterActive = false;
                  } else {_displayedBooks = _originalBooks
                        .where((book) =>
                    (filterType == "书名"
                        ? book.title.contains(_filterText!)
                        : book.author.contains(_filterText!)))
                        .toList();
                  }
                });Navigator.pop(context);
              }, child: Text("确认"),
            ),
            TextButton(onPressed: () {
                Navigator.pop(context);
              }, child: Text("取消"),
            ),
          ],
        );
      },
    );
  }

  // 点击筛选按钮
  Future<void> _showFilterMenu(BuildContext context) async {
    // 菜单位置
    final RenderBox button = context.findRenderObject() as RenderBox;
    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
    final position = RelativeRect.fromRect(
      Rect.fromPoints(
        button.localToGlobal(button.size.topRight(Offset(0, 47)), ancestor: overlay),
        button.localToGlobal(button.size.topRight(Offset(0, 47)), ancestor: overlay),
      ),
      Offset.zero & overlay.size,
    );
    //显示菜单
    await showMenu(context: context, position: position,
      items: [
        // 按书名筛选
        PopupMenuItem(
          child: InkWell(
            onTap: () {Navigator.pop(context);
              _applyFilter("书名");
            },
            child: Row(mainAxisSize: MainAxisSize.min,
              children: [
                Text("按照书名",
                  style: TextStyle(fontSize: 14), softWrap: false,
                ),
                SizedBox(width: 8),
                Icon(Icons.chevron_right, size: 20),
              ],
            ),
          ),
        ),
        // 按作者筛选
        PopupMenuItem(
          child: InkWell(
            onTap: () {Navigator.pop(context);
              _applyFilter("作者");
            },
            child: Row(mainAxisSize: MainAxisSize.min,
              children: [
                Text("按照作者",
                  style: TextStyle(fontSize: 14), softWrap: false,
                ),
                SizedBox(width: 8),
                Icon(Icons.chevron_right, size: 20),
              ],
            ),
          ),
        ),
        if (_isFilterActive)
          // 取消筛选
          PopupMenuItem(
            child: InkWell(
              onTap: () {
                setState(() {
                  _displayedBooks = List.from(_originalBooks);
                  _filterText = '';
                  _isFilterActive = false;
                });
                Navigator.pop(context);
              },
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    "取消筛选",
                    style: TextStyle(fontSize: 14),
                    softWrap: false,
                  ),
                  SizedBox(width: 8),
                  Icon(Icons.clear, size: 20),
                ],
              ),
            ),
          ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    // 显示加载状态
    if (_isLoading) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 20),
              Text('加载书架数据中...'),
            ],
          ),
        ),
      );
    }
    // 显示错误信息
    if (_errorMessage.isNotEmpty) {
      return Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(_errorMessage),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: _fetchBookShelf,
                child: Text('重试'),
              ),
            ],
          ),
        ),
      );
    }
    return PopScope(canPop: false,
        onPopInvokedWithResult: (bool didPop, Object? result) async {
          if (didPop) return;
          // 当用户尝试返回时刷新数据
          await _fetchBookShelf();
          context.pop();
        },
      child:
      Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Text(
          "我的书架",
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        toolbarHeight: 47, elevation: 1,
        actions: [
          Row(
            children: [
              Text('筛选',
                style: TextStyle(fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
              IconButton(
                icon: Icon(
                  Icons.filter_alt_outlined, size: 19,
                  color: _isFilterActive ? Colors.grey : null,
                ),
                onPressed: () => _showFilterMenu(context),
              ),
            ],
          ),
          Row(children: [
              Text('排序',
                style: TextStyle(fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
              IconButton(
                icon: Transform.scale(
                  scaleY: _sortState == 2 ? -1 : 1,
                  child: Icon(Icons.sort, size: 19,
                    color: _sortState != 0 ? Colors.blue : null,
                  ),
                ),
                onPressed: () {
                  setState(() {_sortState = (_sortState + 1) % 3;
                    if (_sortState == 0 && !_isFilterActive) {
                      _displayedBooks = List.from(_originalBooks);
                    } else if (_sortState == 1) {
                      _displayedBooks.sort((a, b) => b.progress.compareTo(a.progress as num ));
                    } else {
                      _displayedBooks.sort((a, b) => a.progress.compareTo(b.progress as num ));
                    }
                  });
                },
              ),
            ],
          ),
        ],
      ),
      body: Padding(padding: EdgeInsets.all(20),
        child: GridView.builder(shrinkWrap: true, itemCount: _displayedBooks.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
            childAspectRatio: 0.53,
          ),
          itemBuilder: (context, index) {
            double bookProgress = double.parse((_displayedBooks[index].progress).toStringAsFixed(1));
            return Column(
              children: [
                // 封面
                Expanded(child: GestureDetector(
                    onTap: () {_handleReadingBook(_displayedBooks[index].title);},
                    child: Container(decoration: BoxDecoration(
                        color: Color(0xFFF5F5F5),
                        borderRadius: BorderRadius.circular(8.0),
                        boxShadow: [
                          BoxShadow(color: Colors.black54,
                            blurRadius: 3, spreadRadius: 2,
                          ),
                        ],
                        image: DecorationImage(
                          image: AssetImage(_displayedBooks[index].image),
                          fit: BoxFit.cover, colorFilter: isDarkMode?
                          ColorFilter.mode(Color(0x80000000),
                            BlendMode.darken,
                          ) :null,
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 3),
                // 标题
                Text(_displayedBooks[index].title,
                  style: TextStyle(fontSize: 13,
                    fontWeight: FontWeight.bold,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
                // 进度
                Row(
                  children: [Expanded(
                        child: Container(decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8.0),
                            color: Colors.grey[300],
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(8.0),
                            child: LinearProgressIndicator(
                              value:  _displayedBooks[index].progress / 100,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
                            ),
                          ),
                        )
                    ),
                    SizedBox(width: 5),
                    Text("${bookProgress}%",
                      style: TextStyle(fontSize: 10,
                        color: Color(0xFF666666),
                      ),
                    ),
                  ],
                ),
              ],
            );
          },
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        type: BottomNavigationBarType.fixed,
        unselectedLabelStyle: const TextStyle(fontSize: 10),
        selectedLabelStyle: const TextStyle(fontSize: 12),
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home_outlined),
            label: "首页",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.menu_book_outlined),
            label: "书架",
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.book_outlined),
            label: "书",
          ),
        ],
        onTap: (int index) {
          setState(() {
            _selectedIndex = index;
          });
          switch(index){
            case 0:
              context.push('/home');
              break;
            case 1:
              context.push('/bookshelf');
              break;
            case 2:
              _handleReadingBook(_defaultBook);
              break;
          }
        },
      ),
    )
    );
  }
}





